package com.spdd.mt.biz.manager.service;

import cn.hutool.core.date.DateUtil;
import com.spdd.mt.biz.config.ConfigBean;
import com.spdd.mt.biz.config.SpddMapping;
import com.spdd.mt.biz.constant.MtOrderStatus;
import com.spdd.mt.biz.constant.NotifyStatus;
import com.spdd.mt.biz.entity.MtProductEntity;
import com.spdd.mt.biz.entity.MtRechargeOrderEntity;
import com.spdd.mt.biz.entity.MtRechargeOrderNotifyEntity;
import com.spdd.mt.biz.exception.NotifyException;
import com.spdd.mt.biz.manager.model.request.OrderNotifyRequest;
import com.spdd.mt.biz.manager.model.request.ProductNotifyRequest;
import com.spdd.mt.biz.service.MtRechargeOrderNotifyService;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.biz.util.StatusUtils;
import com.spdd.mt.common.util.DateUtils;
import com.spdd.mt.common.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class NotifyService {

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private SpddMapping spddMapping;

    @Autowired
    private SignService signService;

    @Autowired
    private MeituanService meituanService;

    @Autowired
    private MtRechargeOrderNotifyService notifyService;

    @Autowired
    private MtRechargeOrderService orderService;

    /**
     * 订单回调推送
     *
     * @param order 订单信息
     */
    @Async
    public void notifyMtOrder(MtRechargeOrderEntity order) {
        // 默认为系统通知
        notifyMtOrder(order, 0);
    }

    /**
     * 订单回调推送
     *
     * @param order      订单信息
     * @param notifyType 通知类型 0 系统， 1 人工
     */
    @Async
    public void notifyMtOrder(MtRechargeOrderEntity order, Integer notifyType) {
        log.info("开始通知请求方");

        SpddMapping.AppInfo appInfo = getAppInfo(order.getMerchNo());

        OrderNotifyRequest notifyRequest = OrderNotifyRequest.builder()
                .mtOrderNo(order.getMtOrderNo())
                .partnerId(appInfo.getPartnerId())
                .partnerOrderNo(order.getOrderNo())
                .partnerOrderStatus(StatusUtils.ORDER_STATUS_MT_MAPPER.getOrDefault(
                        order.getOrderStatus(), MtOrderStatus.ORDER_IN_PROCESS).getValue()
                )
                .finishTime(DateUtils.formatPureDateTime(order.getFinishTime()))
                .build();

        notifyRequest = signService.buildSignRequest(notifyRequest, order.getMerchNo());

        // 保存通知表
        MtRechargeOrderNotifyEntity notifyEntity = MtRechargeOrderNotifyEntity.builder()
                .build();
        notifyEntity.setOrderId(order.getId());
        notifyEntity.setNotifyUrl(order.getNotifyUrl());
        notifyEntity.setNotifyContent(JacksonUtils.toJson(notifyEntity));
        notifyEntity.setNotifyTime(DateUtil.date());
        notifyEntity.setNotifyType(notifyType);
        notifyService.save(notifyEntity);

        // 发送回调信息到美团
        boolean flag;
        try {
            flag = meituanService.sendMtNotify(notifyRequest, order.getNotifyUrl());
        } catch (NotifyException e) {
            flag = false;
        }
        Integer notifyStatus;
        if (flag) {
            notifyStatus = NotifyStatus.SUCCESS.getValue();
        } else {
            notifyStatus = NotifyStatus.FAILED.getValue();
        }

        // 更新订单表通知状态、次数、最新时间
        orderService.updateNotify(order.getId(), order.getTradeMonth(), notifyStatus, DateUtil.date());

        // 更新通知表状态
        MtRechargeOrderNotifyEntity updateEntity = MtRechargeOrderNotifyEntity.builder()
                .id(notifyEntity.getId())
                .notifyStatus(notifyStatus)
                .build();
        notifyService.updateById(updateEntity);
    }

    /**
     * 商品状态变更通知
     *
     * @param merchNo     商户号
     * @param productList 商品集合
     */
    @Async
    public void notifyMtProduct(String merchNo, List<MtProductEntity> productList) {
        SpddMapping.AppInfo appInfo = getAppInfo(merchNo);

        productList.forEach(p -> {
            ProductNotifyRequest notifyRequest = ProductNotifyRequest.builder()
                    .partnerId(appInfo.getPartnerId())
                    .productCode(p.getProductCode())
                    .operationType(p.getMaintenanceStatus())
                    .build();

            notifyRequest = signService.buildSignRequest(notifyRequest, merchNo);

            // 发送信息到美团
            boolean flag;
            try {
                meituanService.sendMtNotify(notifyRequest, configBean.getMtProductNotifyUrl());
            } catch (NotifyException e) {
                log.info("商品状态变更通知失败, error={}", e.getMessage());
            }
        });

    }

    private SpddMapping.AppInfo getAppInfo(String merchNo) {
        return spddMapping.getMapping().get(merchNo);
    }
}
